<?php
/**
 * Created by PhpStorm.
 * User: Eric-pc3
 * Date: 2018/8/2
 * Time: 18:37
 */

namespace app\common\service;

use app\common\logic\GoodsLogic;
use app\common\logic\MemberLogic;
use app\common\logic\SmsLogic;
use think\facade\Log;

class MemberService extends BaseService
{
    /**
     * 收货地址更改   带 ID 为修改 不带为 新增
     * @param array $params 外部提交过来的参数
     * @param int $memberId 当前登录的会员ID
     * @return array
     */
    public function addressChange($params,$memberId){
        if (empty($memberId)) {
            return $this->retError(1011);
        }
        if(empty($params['addressdata']) || !is_array($params['addressdata'])){
            return $this->retError(1,'提交信息出错，请重新提交');
        }
        $addressdata = $params['addressdata'];
        if(empty($addressdata['realname'])){
            return $this->retError(1,'请填写收货人');
        }
        if(empty($addressdata['mobile'])){
            return $this->retError(1,'请填写手机号码');
        }
        $addressdata['mobile'] = preg_replace('# #', '', $addressdata['mobile']);
        if (!isMobilePhone($addressdata['mobile'])) {
            return $this->retError(1,'请填写正确手机号码');
        }
        if(empty($addressdata['areas'])){
            return $this->retError(1,'请选择所在地区');
        }
        if(empty($addressdata['address'])){
            return $this->retError(1,'请填写详细地址');
        }

        $data['member_id'] = $memberId;
        $data['mobile'] = $addressdata['mobile'];
        $data['realname'] = $addressdata['realname'];
        $data['address'] = $addressdata['address'];
        $areas = explode(' ', $addressdata['areas']);
        $data['province'] = $areas[0];
        $data['city'] = $areas[1];
        $data['area'] = $areas[2];

        $memberLogic = new MemberLogic();

        if (empty($params['id'])) {
            // 新增
            // 如果设置为新增的话不需要再查询了
            if (!empty($addressdata['isdefault'])) {
                $data['is_default'] = 1;
            }
            else{
                // 判断 是否 是第一条，第一条默认设置为 默认地址
                $where[] = ['member_id','=',$memberId];
                $addresscount = $memberLogic->_getCountByWhere($where, 0, 'MemberAddress');
                if ($addresscount <= 0) {
                    $data['is_default'] = 1;
                }
            }
            $data['id'] = 0;
        }
        else{
            $data['id'] = $params['id'];
        }

        $jieguo = $memberLogic->save($data,'MemberAddress');

        if($jieguo['err_code'] != 0){
            return $this->retError(1,'收货地址提交失败');
        }

        if (!empty($addressdata['isdefault'])) {
            $memberLogic->_updateAddressDefault($jieguo['data']['id'],$memberId);
        }

        return $this->retSuccess('收货地址提交成功',$jieguo['data']);
    }

    /**
     * 删除地址
     * @param $addressId
     * @param $memberId
     * @return array
     */
    public function addressDelete($addressId,$memberId){
        if (empty($memberId)) {
            return $this->retError(1011);
        }
        if (empty($addressId)) {
            return $this->retError(1,'地址序号不正确');
        }

        $memberLogic = new MemberLogic();
        $where[] = ['member_id','=',$memberId];
        $where[] = ['id','=',$addressId];
        if(false !== $memberLogic->_delAddress($where)){
            return $this->retSuccess('删除成功');
        }
        else{
            return $this->retError(1,'删除失败');
        }
    }

    /**
     * 地址 设置默认地址
     * @param $addressId
     * @param $memberId
     * @return array
     */
    public function addressSetDefault($addressId,$memberId){
        if (empty($memberId)) {
            return $this->retError(1011);
        }
        if (empty($addressId)) {
            return $this->retError(1,'地址序号不正确');
        }

        $memberLogic = new MemberLogic();
        $memberLogic->_updateAddressDefault($addressId,$memberId);
        return $this->retSuccess('设置成功');
    }

    /**
     * 获取收货地址列表
     * @param int $memberId 会员ID
     */
    public function getAddressList($memberId,$keyword){
        if (empty($memberId)) {
            return $this->retError(1011);
        }
        $fields = 'id,realname,mobile,province,city,area,address,is_default';
        $memberLogic = new MemberLogic();
        $where = [];
        if (!empty($keyword)) {
            $where[] = ['realname|mobile','LIKE','%'.$keyword.'%'];
        }
        $addressList = $memberLogic->_getAddressList($memberId,$where, $fields);
        $fanhui = [];
        foreach ($addressList as $item){
            $fanhui[] = [
                'id' => $item['id'],
                'is_default' => $item['is_default'],
                'realname' => $item['realname'],
                'mobile' => $item['mobile'],
                'province' => $item['province'],
                'city' => $item['city'],
                'area' => $item['area'],
                'address' => $item['address'],
            ];
        }
        return $this->retSuccess('收获取收货地址列表成功',$fanhui);
    }

    public function getAddress($addressId){
        $memberLogic = new MemberLogic();
        $address = $memberLogic->_getAddressModelByAddressId($addressId);
        if (empty($address)) {
            return $this->retError(1,'获取收货地址失败');
        }

        return $this->retSuccess('获取收货地址成功',[
            'id' => $address['id'],
            'is_default' => $address['is_default'],
            'realname' => $address['realname'],
            'mobile' => $address['mobile'],
            'province' => $address['province'],
            'city' => $address['city'],
            'area' => $address['area'],
            'address' => $address['address'],
        ]);
    }

    /**
     * 获取默认收货地址（如果没有设置取第一个）
     * @param int $memberId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDefaultAddress($memberId){
        if (empty($memberId)) {
            return $this->retError(1,'会员信息无效，请重新登陆');
        }
        $memberLogic = new MemberLogic();
        $addressList = $memberLogic->_getAddressList($memberId);
        if(count($addressList) < 1){
            return $this->retError(1012);
        }
        $address = [];
        // 取出默认地址
        foreach ($addressList as $item) {
            if($item['is_default'] > 0){
                $address = $item;
                break;
            }
        }

        if (empty($address)) {
            // 找不到默认的，取第一个
            $address = $addressList[0];
        }
        if (empty($address)) {
            return $this->retError(1,'获取收货地址失败');
        }

        return $this->retSuccess('获取收货地址成功',[
            'id' => $address['id'],
            'is_default' => $address['is_default'],
            'realname' => $address['realname'],
            'mobile' => $address['mobile'],
            'province' => $address['province'],
            'city' => $address['city'],
            'area' => $address['area'],
            'address' => $address['address'],
        ]);
    }

    /**
     * 获取 指定 会员的购物车
     * @param $memberId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMemberCartByMemberId($memberId){
        if (empty($memberId)) {
            return $this->retError(1,'会员信息无效，请重新登陆');
        }
        $memberLogic = new MemberLogic();
        $cartList = $memberLogic->_getMemberCartByMemberId($memberId);
        $fanhui = [];
        foreach ($cartList as $item) {
            $fanhui[] = [
                'cart_id' => $item['id'],
                'goods_id' => $item['goods_id'],
                'option_id' => $item['goods_option_id'],
                'goods_thumbs' => getGoodsThumb($item['thumbs']),
                'goods_price' => $item['market_price'],
                'goods_name' => $item['goods_name'],
                'old_market_price' => $item['old_market_price'],
                'option_title' => $item['title'],
                'option_specs' => $item['specs'],
                'total' => $item['total'],
                'selected' => 0, // $item['is_selected'] 不输出 默认 不选中
                'max_total' => $item['stock'],
            ];
        }
        return $this->retSuccess('获取购物车成功',$fanhui);
    }

    /**
     * 添加到 购物车
     * @param $memberId
     * @param $goodsId
     * @param int $total
     * @param int $isSelected
     * @param int $goodsOptionId
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function addGoodsToCart($memberId,$goodsId,$total = 1,$isSelected = 1,$goodsOptionId = 0){
        if (empty($memberId)) {
            return $this->retError(1,'会员信息无效，请重新登陆');
        }
        if (empty($goodsId)) {
            return $this->retError(1,'商品信息无效');
        }
        if (empty($goodsOptionId)) {
            return $this->retError(1,'商品规格无效');
        }
        if ($total < 1) {
            return $this->retError(1,'商品商量不能小于 1 ');
        }

        $goodsLogic = new GoodsLogic();
        $goodsModel = $goodsLogic->_getGoodsById($goodsId);

        if (empty($goodsModel)) {
            return $this->retError(1,'找不到商品');
        }

        $goodsOptionModel = getGoodsOption($goodsModel,$goodsOptionId);
        if(empty($goodsOptionModel)){
            return $this->retError(1,'商品规格获取失败无效');
        }

        $memberLogic = new MemberLogic();
        $jieugo = $memberLogic->_addGoodsToCart($memberId, $total, $goodsModel, $isSelected, $goodsOptionId);
        if($jieugo > 0){
            $fanhui['cart_id'] = $jieugo;
            $fanhui['cart_count'] = $memberLogic->_getMemberCartTotalSumByMemberId($memberId);
            return $this->retSuccess('加入购物车成功',$fanhui);
        }
        else{
            return $this->retError(1,'加入购物车失败');
        }
    }

    /**
     * 减 购物车
     * @param $memberId
     * @param $goodsId
     * @param int $total
     * @param int $goodsOptionId
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function minusGoodsToCart($memberId,$cartId,$total = 1){
        if (empty($memberId)) {
            return $this->retError(1,'会员信息无效，请重新登陆');
        }
        if (empty($cartId)) {
            return $this->retError(1,'购物车 ID 错误');
        }
        if ($total < 1) {
            return $this->retError(1,'商品商量不能小于 1 ');
        }

        $memberLogic = new MemberLogic();
        $jieugo = $memberLogic->_minusCartTotalById($memberId,$cartId, $total);
        if($jieugo > 0){
            $fanhui['cart_id'] = $jieugo;
            $fanhui['cart_count'] = $memberLogic->_getMemberCartTotalSumByMemberId($memberId);
            return $this->retSuccess('更新购物车成功',$fanhui);
        }
        else{
            return $this->retError(1,'更新购物车失败');
        }
    }

    /**
     * 删除购物车里面的商品
     * @param $memberId
     * @param array $cartIds
     * @return array
     */
    public function delCartByIds($memberId,array $cartIds){
        if (empty($memberId)) {
            return $this->retError(1,'会员信息无效，请重新登陆');
        }

        $memberLogic = new MemberLogic();
        $jieguo = $memberLogic->_delCartByIds($memberId, $cartIds);

        if(false === $jieguo){
            return $this->retError(1,'删除购物车商品失败');
        }
        else{
            return $this->retSuccess('删除购物车商品成功');
        }
    }

    /**
     * 更新购物车数量
     * @param $memberId
     * @param $cartId
     * @param $total
     * @return array
     */
    public function updateCartTotalById($memberId,$cartId,$total){
        if (empty($memberId)) {
            return $this->retError(1,'会员信息无效，请重新登陆');
        }
        $memberLogic = new MemberLogic();
        $jieguo = $memberLogic->_updateCartTotalById($memberId, $cartId,$total);

        if(false === $jieguo){
            return $this->retError(1,'更新失败');
        }
        else{
            return $this->retSuccess('更新成功');
        }
    }

    /**
     * 获取会员信息
     * @param $memberId
     * @return array
     */
    public function getMemberInfo($memberId){
        if (empty($memberId)) {
            return $this->retError(1,'会员信息无效，请重新登陆');
        }
        $memberLogic = new MemberLogic();
        $memberModel = $memberLogic->_getMemberByMemberId($memberId);
        if (empty($memberModel)) {
            return $this->retError(1,'找不到会员信息，请重新登陆');
        }

        return $this->retSuccess('获取成功',$memberModel);
    }

    /**
     * 保存会员信息，目前只允许修改  realname  nickname  avatar
     * @param $memberId
     * @param $postData
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setMemberInfo($memberId,$postData){
        if (empty($memberId)) {
            return $this->retError(1,'会员信息无效，请重新登陆');
        }
        $memberLogic = new MemberLogic();
        $updateData['update_time'] = time();
        if (!empty($postData['realname'])) {
            $updateData['realname'] = $postData['realname'];
        }
        if (!empty($postData['nickname'])) {
            $updateData['nickname'] = $postData['nickname'];
        }
        if (!empty($postData['avatar'])) {
            $updateData['avatar'] = $postData['avatar'];
        }
        if (!empty($postData['pwd']) || !empty($postData['pwd2'])) {
            if (empty($postData['pwd']) || empty($postData['pwd2'])) {
                return $this->retError(1,'如不修改密码可不输入两个密码框的密码，否则必须保持两个密码一致');
            }
            if ($postData['pwd'] != $postData['pwd2']) {
                return $this->retError(1,'如不修改密码可不输入两个密码框的密码，否则必须保持两个密码一致');
            }

            $salt = random(8);
            $updateData['pwd'] = encrypt_password($postData['pwd'],$salt);
            $updateData['salt'] = $salt;
        }

        $jieguo = $memberLogic->_updateMemberByMemberId($memberId,$updateData);
        if (false === $jieguo) {
            return $this->retError(1,'更新失败');
        }

        return $this->retSuccess('更新成功');
    }

    public function bindMember($projectId,$memberId,$postData){
        if (empty($memberId)) {
            return $this->retError(1,'会员信息无效，请重新登陆');
        }
        if(empty($postData['mobile'])){
            return $this->retError(1,'请输入11位手机号码');
        }
        if(empty($postData['verifycode'])){
            return $this->retError(1,'请填写短信验证码');
        }
        // TODO 选不开放 密码 先做微信用户的
//        if(empty($postData['pwd'])){
//            return $this->retError(1,'请输入登录密码');
//        }

        if (!isMobilePhone($postData['mobile'])) {
            return $this->retError(1,'请输入正确的手机号码');
        }

        // 验证 短信验证码
        $smsLogic = new SmsLogic($projectId);
        $jieguo = $smsLogic->checkVCode($postData['mobile'],$postData['verifycode']);
        if($jieguo['err_code'] !== 0){
            return $jieguo;
        }

        $memberLogic = new MemberLogic();
        // 当前登录 的 会员
        $memberModel = $memberLogic->_getMemberByMemberId($memberId);
        if (empty($memberModel)) {
            return $this->retError(1,'找不到会员信息，请重新登陆');
        }

        // 手机号码对应的会员
        $where[] = ['mobile','=',$postData['mobile']];
        // 项目 后期 开放
//        $where[] = ['project_id','=',$projectId];
        $mobileModel = $memberLogic->_getMemberByWhere($where);
        // 项目下不存在该 手机号
        if (empty($mobileModel)) {
            $jieguo = $memberLogic->_updateMemberByMemberId($memberId,[
                'mobile' => $postData['mobile'],
            ]);
            if (false === $jieguo) {
                Log::error('手机不存在时，绑定失败 $memberId ' . $memberId . ' mobile ' . $postData['mobile']);

                return $this->retError(1,'绑定失败');
            }
            else{
                return $this->retSuccess('绑定成功');
            }
        }
        if($mobileModel['id'] == $memberId){
            // 输入的手机 和 当前登录的用户是一样的
            return $this->retError(1,'手机号未变更，无需修改');
        }

        // 存在手机号 并且 输入的手机 和 当前登录的用户是不一样的
        if (empty($postData['confirm'])) {
            // 未 确认修改
            // 此手机号已与其他帐号绑定<br>如果继续将会解绑之前帐号<br>确定继续吗？
            return $this->retError(1013);
        }

        $jieguo = $memberLogic->changeMemberMobile($memberId,$mobileModel['id'],$postData['mobile']);

        if ($jieguo['err_code'] != 0) {
            return $this->retError(1,$jieguo['msg']);
        }
        else{
            return $this->retSuccess($jieguo['msg']);
        }
    }

    /**
     * 修改密码
     * @param $projectId
     * @param $memberId
     * @param $postData
     * @return array
     * @throws \Exception
     */
    public function changeMemberPwd($projectId,$memberId,$postData){
        if (empty($memberId)) {
            return $this->retError(1,'会员信息无效，请重新登陆');
        }
        if(empty($postData['mobile'])){
            return $this->retError(1,'请输入11位手机号码');
        }
        if(empty($postData['verifycode'])){
            return $this->retError(1,'请填写短信验证码');
        }

        if(empty($postData['pwd'])){
            return $this->retError(1,'请填写新密码');
        }
        if(empty($postData['pwd1'])){
            return $this->retError(1,'请填写确认密码');
        }

        if($postData['pwd1'] != $postData['pwd']){
            return $this->retError(1,'二次密码不一致');
        }

        if (!isMobilePhone($postData['mobile'])) {
            return $this->retError(1,'请输入正确的手机号码');
        }

        // 验证 短信验证码
        $smsLogic = new SmsLogic($projectId);
        $jieguo = $smsLogic->checkVCode($postData['mobile'],$postData['verifycode']);
        if($jieguo['err_code'] !== 0){
            return $jieguo;
        }

        $memberLogic = new MemberLogic();
        // 当前登录 的 会员
        $memberModel = $memberLogic->_getMemberByMemberId($memberId);
        if (empty($memberModel)) {
            return $this->retError(1,'找不到会员信息，请重新登陆');
        }

        $jieguo = $memberLogic->changeMemberPwdByMobile($postData['mobile'],$postData['pwd']);

        if ($jieguo['err_code'] != 0) {
            return $this->retError(1,$jieguo['msg']);
        }
        else{
            return $this->retSuccess($jieguo['msg']);
        }
    }

    public function sendMemberVCode($scene,$phone){
        $sceneArr = [
            'reg',
            'forget',
        ];
        if(empty($phone)){
            return $this->retError(1,'手机号码不能为空');
        }
        if(!isMobilePhone($phone)){
            return $this->retError(1,'手机号码格式不正确');
        }
        if (!in_array($scene, $sceneArr)) {
            return $this->retError(1,'未知场景');
        }
        if ('reg' == $scene) {
            // 注册时，先检测手机号是否存在
            $memberLogic = new MemberLogic();
            $where[] = ['delete_time','<',1];
            $where[] = ['mobile','=',$phone];
            $count = $memberLogic->_getCountByOriginalWhere($where,'Member');
            if ($count > 0) {
                return $this->retError(1, '账号已存在');
            }
        } elseif ('forget' == $scene) {
            // 找回密码时，先检测手机号是否存在
            $memberLogic = new MemberLogic();
            $where[] = ['delete_time','<',1];
            $where[] = ['mobile','=',$phone];
            $count = $memberLogic->_getCountByOriginalWhere($where,'Member');
            if ($count < 1) {
                return $this->retError(1, '账号未注册');
            }
        }
        $smsLogic = new SmsLogic(getProjectId());
        $jieguo = $smsLogic->sendVcode($phone);

        if($jieguo['err_code'] != 0){
            return $this->retError(1, $jieguo['msg']);
        }
        else{
            return $this->retSuccess($jieguo['msg'],$jieguo['data']);
        }
    }

    public function regMember($params){
        $memberLogic = new MemberLogic();
        $jieguo = $memberLogic->regMember($params);
        if($jieguo['err_code'] != 0){
            return $this->retError(1, $jieguo['msg']);
        }
        else{
            return $this->retSuccess($jieguo['msg']);
        }
    }

    public function loginByMobileAndPwd($mobile,$pwd){
        $memberLogic = new MemberLogic();
        $jieguo = $memberLogic->loginByMobileAndPwd($mobile, $pwd);
        if ($jieguo['err_code'] !== 0) {
            return $this->retError(1, $jieguo['msg']);
        }
        else{
            return $this->retSuccess($jieguo['msg'],$jieguo['data']);
        }
    }

    public function forgetPass($params){
        if (empty($params['mobile'])) {
            return $this->retError(1, '请输入手机号码');
        }
        if(empty($params['vcode'])){
            return $this->retError(1,'短信验证码不能为空');
        }
        if(empty($params['pwd'])){
            return $this->retError(1,'密码不能为空');
        }
        if(empty($params['pwd2'])){
            return $this->retError(1,'确认密码不能为空');
        }

        if(!isMobilePhone($params['mobile'])){
            return $this->retError(1,'手机号不正确');
        }

        if($params['pwd'] !== $params['pwd2']){
            return $this->retError(1,'密码和确认密码不一致');
        }

        // 验证 短信验证码
        $smsLogic = new SmsLogic(getProjectId());
        $jieguo = $smsLogic->checkVCode($params['mobile'],$params['vcode']);
        if($jieguo['err_code'] !== 0){
            return $jieguo;
        }
        // 短信验证码 验证通过
        $memberLogic = new MemberLogic();
        return $memberLogic->changeMemberPwdByMobile($params['mobile'], $params['pwd2']);
    }
}